package com.kujie.service;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kujie.constant.SceneConstant;
import com.kujie.domain.query.SceneQuery;
import com.kujie.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springaicommunity.mcp.annotation.McpTool;
import org.springaicommunity.mcp.annotation.McpToolParam;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * 智云mcp工具
 *
 * @author check
 * @date 2025-07-28
 */
@Slf4j
@Service
public class SceneService {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取场景列表
     */
    @McpTool(name = "get_scene_list", description = "获取场景列表，此工具无参数输入")
    public String getSceneList() {
        log.info("获取场景列表工具调用");
        ResponseEntity<String> response = HttpUtils.get(SceneConstant.SCENE_LIST, null, new ParameterizedTypeReference<String>() {
        });
        return response.getBody();
    }


    /**
     * 保存场景
     *
     * @param sceneQueryString 场景信息
     * @return 保存结果
     */
    @McpTool(name = "save_scene", description = "保存场景，本方法是用来保存要创建的场景，调用之前先要获取场景列表根据场景名称判断是否已经存在，如果场景已经存在则直接提示用户场景已经存在并且直接结束。如果与灯光/照明有关则调用获取照明/灯光设备列表信息，与空调有关调用获取空调设备列表")
    public String saveScene(@McpToolParam(description = "创建场景参数") String sceneQueryString) {
        log.info("开始解析场景参数");

        try {
            // 参数清理
            if (sceneQueryString == null || sceneQueryString.isEmpty()) {
                log.warn("场景参数为空");
                return "场景参数不能为空";
            }

            sceneQueryString = sceneQueryString.trim();
            log.info("参数长度: {}", sceneQueryString.length());

            // 使用Jackson解析作为备选方案
            SceneQuery sceneQuery = objectMapper.readValue(sceneQueryString, SceneQuery.class);
            log.info("成功解析场景参数, 场景名称: {}", sceneQuery.getSceneName());

            ResponseEntity<String> response = HttpUtils.post(SceneConstant.SAVE_SCENE, null, sceneQuery, new ParameterizedTypeReference<String>() {
            });
            return response.getBody();
        } catch (Exception e) {
            log.error("解析场景参数失败: {}", e.getMessage(), e);
            log.error("问题参数内容: {}", sceneQueryString);
            return "解析场景参数失败: " + e.getMessage();
        }
    }
}
